package com.ybear.ybutils.utils

import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.text.TextUtils
import com.ybear.ybutils.utils.AppUtil.getPackageName
import org.json.JSONObject

/**
 * 启动页面工具类
 */
object StartUtils {
    /**
     * 启动Activity
     * @param context      Activity
     * @param intent        传入的数据
     * @return              启动结果
     */
    @JvmStatic
    fun startActivity(context: Context?, intent: Intent?): Boolean {
        if( context == null ) return false
        context.startActivity( intent )
        return true
    }

    /**
     * 启动Activity
     * @param context          Activity
     * @param packageName       包名
     * @param action            在Intent中传入的Action
     * @param data              携带的启动参数
     * @param <T>               启动参数的类型
     * @return                  启动结果
    </T> */
    @JvmStatic
    fun <T> startActivity(context: Context?, packageName: String?, action: String?, data: T?): Boolean {
        return try {
            if ( context == null ) return false
            val intent = when {
                action.isNullOrEmpty() && data == null -> Intent().setAction(action)
                data is Class<*> -> Intent( context, data as Class<*> )
                data is Uri -> Intent( action, data )
                data is String -> Intent( action, Uri.parse( ObjUtils.parseString( data ) ) )
                data is Intent -> Intent( data )
                else -> Intent( action )
            }
            intent.setPackage( packageName )
            startActivity( context, intent )
        } catch (e: Exception) {
            false
        }
    }

    /**
     * 启动Activity
     * @param context          Activity
     * @param action            在Intent中传入的Action
     * @param data              携带的启动参数。通常为Uri地址
     * @return                  启动结果
     */
    @JvmStatic
    fun startActivity(context: Context?, action: String?, data: String): Boolean {
        return startActivity( context, null, action, data )
    }

    /**
     * 启动Activity
     * @param context          Activity
     * @param action            在Intent中传入的Action
     * @return                  启动结果
     */
    @JvmStatic
    fun startActivity(context: Context?, action: String?): Boolean {
        return startActivity<Any?>( context, null, action, null )
    }

    /**
     * 打开谷歌商店
     * @param context       上下文
     * @return              结果
     */
    @Deprecated(
        "The method is not perfect and has been abandoned.",
        replaceWith = ReplaceWith( "startStore(Context?, String?)" )
    )
    @JvmOverloads
    @JvmStatic
    fun startGooglePlay(context: Context?,
                        packageName: String? = context?.let { getPackageName( it ) }): Boolean {
        packageName ?: return false // 没有包名直接返回
        // 优先尝试打开 Google Play 应用
        val playStoreIntent = Intent( Intent.ACTION_VIEW ).apply {
            data = Uri.parse("market://details?id=$packageName")
            setPackage("com.android.vending")
        }
        try {
            context?.startActivity(playStoreIntent)
            return true
        } catch (e: ActivityNotFoundException) {
            // Google Play 不可用，使用浏览器打开
            val browserIntent = Intent(Intent.ACTION_VIEW).apply {
                data = Uri.parse("https://play.google.com/store/apps/details?id=$packageName")
            }
            context?.startActivity(browserIntent)
        }
        return false //  如果 startActivity 失败，返回 false
    }

    /**
     * 打开华为商店
     * @param context       上下文
     * @return              结果
     */
    @Deprecated(
        "The method is not perfect and has been abandoned.",
        replaceWith = ReplaceWith( "startStore(Context?, String?)" )
    )
    @JvmStatic
    fun startMarketDetailsOfHW(context: Context?): Boolean {
        if (context == null) return false
        try {
            val pkName = getPackageName(context)
            //脱敏处理
            val json = JSONObject(
                Base64Utils.decodeBase64String(
                    "eyJhIjoiY29tLmh1YXdlaS5hcHBtYXJrZXQiLCJiIjoiLmludGVudC5hY3Rpb24uQXBwRGV0YWlsIiwiYyI6Imh0dHBzOi8vYXBwZ2FsbGVyeS5jbG91ZC5odWF3ZWkuY29tL2FwcERldGFpbD9wa2dOYW1lPSJ9"
                )
            )
            //com.huawei.appmarket
            val url = if (json.has("a")) json.getString("a") else ""
            //.intent.action.AppDetail
            val detail = if (json.has("b")) json.getString("b") else ""
            //https://appgallery.cloud.huawei.com/appDetail?pkgName=
            val data = if (json.has("c")) json.getString("c") else ""
            val intent = Intent(url + detail)
            intent.setPackage(url)
            intent.putExtra("APP_PACKAGENAME", pkName)
            if (startActivity(context, intent)) return true
            //https://appgallery.cloud.huawei.com/appDetail?pkgName=
            return startActivity(
                context,
                Intent.ACTION_VIEW,
                data + pkName
            )
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return false
    }

    /**
     * 打开商店内App的详情页（通用模式，仅支持该操作的商店可用）
     * @param context       上下文
     * @return              打开结果
     */
    @Deprecated(
        "The method is not perfect and has been abandoned.",
        replaceWith = ReplaceWith( "startStore(Context?, String?)" )
    )
    @JvmStatic
    fun startMarketDetails(context: Context?): Boolean {
        return startActivity(
            context,
            getPackageName(context!!),
            Intent.ACTION_VIEW,
            Uri.parse("market://details?id=" + getPackageName(context))
        )
    }

    /**
     * 打开厂商对应的应用详情页（通用模式）
     * 支持机型     Google | 华为 | 小米 | VIVO | OPPO | 三星
     */
    @JvmOverloads
    @JvmStatic
    fun startStore(
        context: Context?,
        chooserTitle: String? = null,
        packageName: String? = context?.let { getPackageName( it ) },
    ): Boolean {
        return StartStore.start( context, chooserTitle, packageName )
    }

    /**
     * 打开Facebook页面
     * @param context                     上下文
     * @param url                         eg:"https://www.facebook.com/页面名称-页面ID"
     * @return                            跳转结果
     */
    @JvmOverloads
    @JvmStatic
    fun startFacebookPage(
        context: Context?,
        url: String,
        isAllowJumpGooglePlay: Boolean = true,
        chooserTitle: String? = null
    ): Boolean {
        if (context == null || TextUtils.isEmpty(url)) return false
        val packageName = "com.facebook.katana"
        try {
            context.packageManager.getPackageInfo(packageName, 0)
            val result = startActivity(
                context,
                null,
                Intent.ACTION_VIEW,
                "fb://page/" + url.substring(url.lastIndexOf("-") + 1)
            )
            if (result) return true
            //跳转失败
            throw ActivityNotFoundException(url)
        } catch (e: Exception) {
            if (startActivity(context, Intent.ACTION_VIEW, url)) return true
            //跳转商店页
            return isAllowJumpGooglePlay && startStore( context, chooserTitle, packageName )
        }
    }

    /**
     * 打开WhatsApp
     * @param context                     上下文
     * @param mobileNum                   WhatsApp号码
     * @return                            跳转结果
     */
    @JvmOverloads
    @JvmStatic
    fun startWhatsApp(
        context: Context?,
        mobileNum: String,
        isAllowJumpGooglePlay: Boolean = true,
        chooserTitle: String? = null
    ): Boolean {
        val packageName = "com.whatsapp"
        val url = "https://api.whatsapp.com/send?phone=$mobileNum"
        try {
            if (startActivity(context, packageName, Intent.ACTION_VIEW, url)) return true
            //跳转失败
            throw ActivityNotFoundException(url)
        } catch (e: Exception) {
            //跳转商店页
            return isAllowJumpGooglePlay && startStore( context, chooserTitle, packageName )
        }
    }

    /**
     * 打开邮箱
     * @param context             上下文
     * @param address             邮箱地址
     * @return                    结果
     */
    @JvmStatic
    fun startEmail(context: Context?,
                   address: String,
                   title: String? = null,
                   content: String? = null,
                   chooserTitle: String? = null
    ): Boolean {
        if (context == null || TextUtils.isEmpty(address)) return false
        val intent = Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:$address"))
        //邮件地址
        intent.putExtra(Intent.EXTRA_EMAIL, address)
        //邮件标题
        if (!TextUtils.isEmpty(title)) intent.putExtra(Intent.EXTRA_SUBJECT, title)
        //邮件内容
        if (!TextUtils.isEmpty(content)) intent.putExtra(Intent.EXTRA_TEXT, content)
        //默认/可选其他邮箱
        return startActivity(
            context,
            if (TextUtils.isEmpty(chooserTitle)) intent else Intent.createChooser(
                intent,
                chooserTitle
            )
        )
    }

    /**
     * 打开邮箱
     * @param context             上下文
     * @param address             邮箱地址
     * @param title               标题
     * @param content             内容
     * @param chooserTitleResId   选择邮箱的标题资源id
     * @return                    结果
     */
    @JvmStatic
    fun startEmail(context: Context?,
                   address: String,
                   title: String?,
                   content: String?,
                   chooserTitleResId: Int
    ): Boolean {
        return context != null && startEmail(
            context, address, title, content,
            context.resources.getString( chooserTitleResId )
        )
    }
}
